import WebsocketLifecycle from '@/api/websocket/websocketLifecycle'

let ws: {
    [index: symbol]: WebSocket
} = {}
const websocketUrl: string = `${process.env.websocket_base_url}`
const timeout: number = 5000
let timer: {
    [index: symbol]: number | NodeJS.Timeout
} = {}
let noConnect: {
    [index: symbol]: boolean
} = {}

// websocket路径携带organization
function getWebsocketHeader () {
    const url = location.pathname.split('/')
    if (url.length <= 3) {
        return websocketUrl
    }

    const urlObj = new URL(websocketUrl)
    return `${urlObj.origin}/${url[1] + urlObj.pathname}`
}
/**
 * @function 创建一个新的websocket
 * @param key {symbol} 每次创建一个新的ws的时候传入一个新的symbol,
 * 这个symbol即表示此次连接的唯一id，后续关闭连接的时候依然传入此symbol
 * @return void
 */
function createWs (key: symbol) {
    // 创建websocket 实例
    ws[key] = new WebSocket(getWebsocketHeader())
    initEventHandler(key)
}

function initEventHandler (key: symbol) {
    // WebsocketLifecycle.onopen && (ws.onopen = WebsocketLifecycle.onopen)

    ws[key].onmessage = WebsocketLifecycle.onmessage

    ws[key].onclose = function () {
        WebsocketLifecycle.onclose()
        if (noConnect[key]) {
            delete noConnect[key]
            return
        }
        timer[key] = setTimeout(function () {
            createWs(key)
        }, timeout)
    }
}

function sendWsDataToApp (key, data) {
    data && ws[key].send(data)
}

function closeWs (key) {
    noConnect[key] = true
    clearTimeout(timer[key] as number)
    delete timer[key]
    ws[key].close()
    delete ws[key]
}

export default ({ Vue }: { Vue: MgVue }) => {
    // 定义websocket向后端发送数据的方法, 在组件中使用: this.$ws_send('123'); 在js文件中使用: Vue.prototype.$ws_send('123')
    Vue.prototype.$wsSend = sendWsDataToApp
    Vue.prototype.$closeWs = closeWs
    Vue.prototype.$createWs = createWs
}
